<template>
  <div class="ai-chat-support" :class="{ 'expanded': isExpanded }">
    <!-- AI客服按钮 -->
    <div class="ai-chat-button" @click="toggleChat">
      <span v-if="!isExpanded" class="ai-icon">🤖</span>
      <span v-else class="close-icon">✕</span>
    </div>

    <!-- 聊天窗口 -->
    <div v-if="isExpanded" class="chat-window">
      <div class="chat-header">
        <div class="header-content">
          <div class="ai-avatar">
            <span>🤖</span>
          </div>
          <div class="header-text">
            <h3>AI智能助手</h3>
            <p>随时为您解答问题</p>
          </div>
        </div>
        <el-button
          type="danger"
          size="small"
          @click="clearHistory"
          plain
          round>
          清屏
        </el-button>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index"
             :class="['message', message.type]">
          <!-- 用户消息 -->
          <div v-if="message.type === 'sent'" class="message-sent">
            <div class="message-content user-message">
              <div class="message-text">{{ message.text }}</div>
            </div>
            <div class="user-avatar">
              <span>👤</span>
            </div>
          </div>

          <!-- AI消息 -->
          <div v-else class="message-received">
            <div class="ai-avatar">
              <span>🤖</span>
            </div>
            <div class="message-content ai-message">
              <div class="message-text" v-html="message.htmlText || message.text"></div>
              <div class="typing-indicator" v-if="message.isTyping">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </div>
            </div>
          </div>

          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>

      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          placeholder="请输入您的问题..."
          @keyup.enter="sendMessage"
          :disabled="sendingMessage"
          type="textarea"
          :rows="2"
          resize="none"
        />
        <el-button
          type="primary"
          @click="sendMessage"
          :loading="sendingMessage"
          :disabled="!inputMessage.trim()"
          round
          class="send-button">
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onUnmounted } from 'vue'
import { ElInput, ElButton } from 'element-plus'
import { sendAIMessage } from '@/api/AIChatApi'

const isExpanded = ref(false)
const inputMessage = ref('')
const messages = ref([
  {
    type: 'received',
    text: '您好！我是AI智能助手，有什么我可以帮您的吗？',
    time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
])
const sendingMessage = ref(false)
const messagesContainer = ref(null)
const typingTimers = ref([])

const toggleChat = () => {
  isExpanded.value = !isExpanded.value
}

const typeMessage = (messageIndex, fullText, speed = 20) => {
  const message = messages.value[messageIndex]
  message.htmlText = ''
  message.isTyping = true

  let i = 0
  const timer = setInterval(() => {
    if (i < fullText.length) {
      message.htmlText += fullText.charAt(i)
      i++
      scrollToBottom()
    } else {
      clearInterval(timer)
      message.isTyping = false
      scrollToBottom()
    }
  }, speed)

  typingTimers.value.push(timer)
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || sendingMessage.value) return

  // 添加用户消息到界面
  const userMessage = {
    type: 'sent',
    text: inputMessage.value,
    time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  messages.value.push(userMessage)
  const userText = inputMessage.value
  inputMessage.value = ''
  sendingMessage.value = true

  scrollToBottom()

  // 添加AI正在输入的占位消息
  const aiPlaceholderIndex = messages.value.length
  const aiPlaceholder = {
    type: 'received',
    text: '',
    htmlText: '',
    isTyping: true,
    time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  messages.value.push(aiPlaceholder)

  scrollToBottom()

  try {
    // 获取用户ID
    const userId = localStorage.getItem('user_id') || null

    console.log('发送请求:', { question: userText, user_id: userId }) // 调试日志

    // 调用AI接口
    const response = await sendAIMessage(userText, userId)

    console.log('收到响应:', response) // 调试日志

    // 检查响应状态
    if (response && response.data) {
      // 更新AI回复
      const fullText = response.data.answer || response.data.reply || response.data.message || response.data.response || '抱歉，我没有理解您的问题。'
      typeMessage(aiPlaceholderIndex, fullText)
    } else {
      throw new Error('服务器返回格式不正确')
    }
  } catch (error) {
    console.error('AI客服调用失败:', error)

    // 显示错误消息
    let errorMessage = '抱歉，AI客服暂时无法回应，请稍后再试。'

    // 根据错误类型提供更具体的提示
    if (error.response) {
      if (error.response.status === 404) {
        errorMessage = 'AI客服服务未找到，请联系管理员。'
      } else if (error.response.status === 500) {
        errorMessage = '服务器内部错误，请稍后再试。'
      } else if (error.response.status === 422) {
        errorMessage = '请求参数格式不正确，请重新尝试。'
        console.error('请求参数验证失败:', error.response.data)
      } else if (error.response.status === 400) {
        errorMessage = '请求参数错误，请重新尝试。'
      }
    } else if (error.request) {
      errorMessage = '网络连接失败，请检查网络设置。'
    } else if (error.code === 'ECONNABORTED') {
      errorMessage = '请求超时，请稍后重试。AI处理可能需要较长时间。'
    }

    // 更新错误消息
    typeMessage(aiPlaceholderIndex, errorMessage)
  } finally {
    sendingMessage.value = false
    scrollToBottom()
  }
}

const clearHistory = () => {
  // 清除所有打字定时器
  typingTimers.value.forEach(timer => clearInterval(timer))
  typingTimers.value = []

  // 重置消息列表
  messages.value = [
    {
      type: 'received',
      text: '您好！我是AI智能助手，有什么我可以帮您的吗？',
      time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
  ]
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 组件卸载时清除所有定时器
onUnmounted(() => {
  typingTimers.value.forEach(timer => clearInterval(timer))
})
</script>

<style scoped>
.ai-chat-support {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 1000;
}

.ai-chat-button {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #64b5f6);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  cursor: pointer;
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  outline: none;
}

.ai-chat-button:hover {
  transform: scale(1.1) rotate(10deg);
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.4);
}

.ai-chat-button:active {
  transform: scale(0.95);
}

.chat-window {
  position: absolute;
  bottom: 70px;
  right: 0;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 12px 36px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-header {
  background: linear-gradient(135deg, #409eff, #64b5f6);
  color: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.ai-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.header-text h3 {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
}

.header-text p {
  margin: 0;
  font-size: 12px;
  opacity: 0.9;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f8fafc;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  display: flex;
  flex-direction: column;
}

.message-sent {
  align-items: flex-end;
  display: flex;
  flex-direction: row-reverse;
  gap: 10px;
}

.message-received {
  align-items: flex-start;
  display: flex;
  gap: 10px;
}

.user-avatar, .ai-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}

.user-avatar {
  background: linear-gradient(135deg, #64b5f6, #409eff);
  color: white;
}

.ai-avatar {
  background: linear-gradient(135deg, #a5d6a7, #81c784);
  color: white;
}

.message-content {
  max-width: 75%;
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-message {
  background: linear-gradient(135deg, #409eff, #64b5f6);
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message {
  background: white;
  color: #333;
  border-bottom-left-radius: 4px;
  border: 1px solid #e2e8f0;
}

.message-text {
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.typing-indicator {
  display: flex;
  align-items: center;
  padding: 10px 0 5px;
}

.dot {
  width: 8px;
  height: 8px;
  background-color: #94a3b8;
  border-radius: 50%;
  margin-right: 6px;
  animation: typing 1.4s infinite ease-in-out;
}

.dot:nth-child(1) {
  animation-delay: 0s;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
  margin-right: 0;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-5px);
  }
}

.message-time {
  font-size: 11px;
  color: #94a3b8;
  margin-top: 6px;
  align-self: flex-end;
}

.chat-input {
  display: flex;
  flex-direction: column;
  padding: 15px;
  background-color: white;
  border-top: 1px solid #e2e8f0;
  gap: 10px;
}

.chat-input :deep(.el-textarea__inner) {
  border-radius: 16px;
  padding: 12px 16px;
  resize: none;
  border: 1px solid #e2e8f0;
  transition: border-color 0.3s;
}

.chat-input :deep(.el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.send-button {
  align-self: flex-end;
  padding: 8px 20px;
  font-weight: 500;
  transition: all 0.3s;
}

.send-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c0c0c0;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0;
}
</style>
